package com.hhj.sell.service.impl;

import com.hhj.sell.converter.OrderMaster2OrderdDTO;
import com.hhj.sell.dao.OrderDetailDao;
import com.hhj.sell.dao.OrderMasterDao;
import com.hhj.sell.dto.CartDTO;
import com.hhj.sell.dto.OrderDTO;
import com.hhj.sell.enums.OrderStatusEnum;
import com.hhj.sell.enums.PalyStatusEnum;
import com.hhj.sell.enums.ResultEnums;
import com.hhj.sell.exception.SellException;
import com.hhj.sell.pojo.OrderDetail;
import com.hhj.sell.pojo.OrderMaster;
import com.hhj.sell.pojo.ProductInfo;
import com.hhj.sell.service.OrderService;
import com.hhj.sell.service.ProductInfoService;
import com.hhj.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    /*创建订单的逻辑*/
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private OrderMasterDao orderMasterDao;
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        String orderId = KeyUtil.genUniquekey();
        /*查询商品的数量价格*/
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findById(orderDetail.getProductId());
            if (productInfo == null){
                throw new SellException(ResultEnums.PRODUCT_NOT_EXIST);
            }
            /*计算总价*/
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
            /*2.封装商品详情信息*/
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetail.setDetailId(KeyUtil.genUniquekey());
            orderDetail.setOrderId(orderId);
            orderDetailDao.save(orderDetail);
        }
        /*3.写入订单数据*/
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPalyStauts(PalyStatusEnum.WAIT.getCode());
        orderMaster.setOrderAmount(orderAmount);
        orderMasterDao.save(orderMaster);
        /*减库存*/
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO findById(String orderId) {
        OrderDTO orderDTO = new OrderDTO();
        OrderMaster orderMaster = orderMasterDao.findById(orderId).get();
        if (orderMaster == null) {
            new SellException(ResultEnums.ORDERMATER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = orderDetailDao.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            new SellException(ResultEnums.ORDERDETAIL_NOT_EXIST);
        }
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    @Transactional
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterDao.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderMaster> orderMasterList = orderMasterPage.getContent();
        List<OrderDTO> orderDTOList = OrderMaster2OrderdDTO.converter(orderMasterList);
       /* for (OrderMaster orderMaster : orderMasterList) {
            List<OrderDetail> orderDetailList = orderDetailDao.findByOrderId(orderMaster.getOrderId());
            if (!CollectionUtils.isEmpty(orderDetailList)){
                for (OrderDTO orderDTO : orderDTOList) {
                    orderDTO.setOrderDetailList(orderDetailList);
                }
            }
        }*/
        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        /*查询订单的状态*/
       if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
           log.error("【取消订单】订单状态不正确，order={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
           throw new SellException(ResultEnums.ORDER_STATUS_ERROR);
       }
        /*修改订单的状态*/
//        OrderMaster orderMaster = orderMasterDao.findById(orderDTO.getOrderId()).get();
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterDao.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败，ordermaster={}",orderMaster);
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }
        /*加库存*/
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情，orderDTO={}",orderDTO);
            throw new SellException(ResultEnums.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);
        /*已支付退钱*/
        if (orderDTO.getPalyStauts().equals(PalyStatusEnum.SUCCESS)) {
            //TODO
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        /*判断订单状态*/
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【完结订单】订单状态不正确，order={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnums.ORDER_STATUS_ERROR);
        }
        /*修改订单的状态*/
//        OrderMaster orderMaster = orderMasterDao.findById(orderDTO.getOrderId()).get();
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.FINASHEND.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterDao.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败，ordermaster={}",orderMaster);
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        /*判断订单状态*/
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【订单支付完成】订单状态不正确，order={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnums.ORDER_STATUS_ERROR);
        }
        /*判断支付状态*/
        if (!orderDTO.getPalyStauts().equals(PalyStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】支付状态不正确，order={},palyStatus={}",orderDTO.getOrderId(),orderDTO.getPalyStauts());
            throw new SellException(ResultEnums.ORDER_PAY_STATUS_ERROR);
        }
        /*修改支付状态*/
        OrderMaster orderMaster = orderMasterDao.findById(orderDTO.getOrderId()).get();
        orderDTO.setPalyStauts(PalyStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterDao.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败，ordermaster={}",orderMaster);
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }
}
